package com.bm.service.Impl;

import com.bm.enums.OrderStatus;
import com.bm.exception.BusinessException;
import com.bm.exception.ExceptionCode;
import com.bm.model.Order;
import com.bm.service.IOrderRepository;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class OrderRepositoryImpl implements IOrderRepository {
    //orders 是一个 ConcurrentHashMap，用于存储订单数据。键是订单 ID，值是订单对象。
    // ConcurrentHashMap 提供了线程安全的存储，
    // 但在高并发场景下可能仍存在一些竞争条件，因此该实现主要适用于测试环境。
    private final Map<String, Order> orders = new ConcurrentHashMap<>();



    @Override
    public void save(Order order) {
        if (order == null) {
            throw new IllegalArgumentException("Order cannot be null");
        }
        String orderId = order.getOrderId();
        if (orderId == null) {
            throw new IllegalArgumentException("Order ID cannot be null");
        }
        orders.put(orderId, order);
    }


    @Override
    public Order findById(String orderId) {
        Order order = orders.get(orderId);
        if (order == null) {
            throw new BusinessException(ExceptionCode.ORDER_NOT_FOUND);
        }
      return order;
    }

    @Override
    public void updateStatus(String orderId, OrderStatus status) {
        Order order = orders.get(orderId);
        if (order == null) {
            throw new BusinessException(ExceptionCode.ORDER_NOT_FOUND);
        }
        order.setStatus(status);

    }
}
